<template>
  <div class="login">
    <van-nav-bar title="登录页"/>
    <van-form @submit="userLogin" @failed = "onFailed">
        <van-field
            v-model="userInfo.mobile"
            required
            label="手机号"
            placeholder="请输入手机号码"
             :rules="[{ pattern:/^1[3-9]\d{9}$/, message: '请输入正确的手机号'}]"
        />
        <van-field
            v-model="userInfo.code"
            required
            label="验证码"
            placeholder="请输入验证码"
            :rules="[{ pattern: /^\d{6}$/, message: '请输入验证码' }]"
        />
        <div style="margin: 16px;">
            <van-button round block type="info" native-type="submit" @click="userLogin">
            提交
            </van-button>
            <van-button round type="info" class="btn" @click="hTest">获取个人信息</van-button>
         当前是否登陆？{{ $store.state.tokenInfo.token ? '已登录' : '未登录' }}
        </div>
    </van-form>
  </div>
</template>

<script>
import { login, getProfile } from '@/api/user'
export default {
  name: 'Login',
  data () {
    return {
      userInfo: {
        code: '246810',
        mobile: '13912345678'
      }
    }
  },
  methods: {
    hTest () {
      getProfile()
    },
    //   表单验证
    onFailed (errorInfo) {
      console.log('failed', errorInfo)
    },
    async userLogin () {
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true
      })
      // 这个是解构
      const { mobile, code } = this.userInfo
      try {
        const res = await login(mobile, code)
        // 登录成功后保存token
        this.$store.commit('mSetTokenInfo', res.data.data)
        // 验证token   这个不能写在上边这句话上边
        const profile = await getProfile()
        console.log(profile)
        console.log(res)
        this.$router.push('/')
        this.$toast.success('登陆成功')
      } catch (error) {
        console.log(error)
        this.$toast.fail('登陆失败')
      }
    }
  }
}
</script>
